'use strict';
const crypto = require('crypto')
const db = uniCloud.database();
const { getOffsetDate, getNowFormatDate } = require('time')
exports.main = async (event, context) => {
	if (event.action === 'addTakein') {
		const {
			openId,
			goodsInOrder
		} = event.data
		const uid = openId
		
		const order_id = parseInt(Date.now() / 1000) + crypto.createHash('md5').update(uid, 'utf-8').digest('hex')
			.substring(0, 8);
		// 计算订单总金额
		const totalFee = goodsInOrder.reduce((acc, cur) => acc + cur.number * cur.price, 0)
		// 门店位置
		const chooseStore = event.data.chooseStore
		const remark = event.data.remark
		// 生成订单
		const orderResult = await db.collection('orders').add({
			uid, // 用户openId
			order_id, // 用户和时间编译的订单号
			order_type: 0, // 0为自取订单,1为外卖
			goodsInOrder, // 购物车列表
			totalFee, // 订单总价
			chooseStore, // 选择的门店
			status: 1,
			createOrderTime: new Date().getTime(),
			takeTime: new Date(),
			remark,
			payment_channel: 'wxpay'
		})

		if (!orderResult.id) {
			return {
				code: -3,
				msg: '提交订单失败,请稍后再试'
			}
		}

		return {
			order_id
		}
	} else if (event.action === 'addTakeout') {
		const {
			openId,
			goodsInOrder
		} = event.data
		const uid = openId
		
		const order_id = parseInt(Date.now() / 1000) + crypto.createHash('md5').update(uid, 'utf-8').digest('hex')
			.substring(0, 8);
		// 计算订单总金额
		const totalFee = goodsInOrder.reduce((acc, cur) => acc + cur.number * cur.price, 0)
		const order_address = event.data.order_address
 		const remark = event.data.remark
		const orderResult = await db.collection('orders').add({
			uid, // 用户openId
			order_id, // 用户和时间编译的订单号
			order_type: 1, // 0为自取订单,1为外卖
			goodsInOrder, // 购物车列表
			totalFee, // 订单总价
			order_address, // 选择的门店
			status: 1,
			createOrderTime: new Date().getTime(),
			takeTime: new Date().getTime(),
			remark,
			payment_channel: 'wxpay'
		})

		if (!orderResult.id) {
			return {
				code: -3,
				msg: '提交订单失败,请稍后再试'
			}
		}

		return {
			order_id
		}
	} else if(event.action === 'getOrder') {
		console.log('event',event)
		let order_id = event.order_id
		const resResult = await db.collection('orders').where({order_id}).get()
		console.log('resResult', resResult)
		return resResult
	} else if(event.action === 'orderCurrent'){
		let order_id = event.order_id
		console.log('order_id', order_id)
		//判断status状态
		const status = await db.collection('orders').where({order_id}).field({status:1})
		.get().then(res => {
			return res.data[0].status
		})
		if(status === 2) {
			// 通过订单查询门店
			const store = await db.collection('orders').where({order_id}).field({chooseStore:1})
			.get().then(res => {
				console.log('time222===>', res)
				return res.data[0].chooseStore
			})
			const num = await db.collection('orders')
			.where({
				status: 3,
				chooseStore: store
			})
			.count().then(res => {
				return res.total
			})
			
			let time = getOffsetDate(8)
			let nowTime = getNowFormatDate(time)
			// 计算取餐时间
			const nTime = new Date(time.setMinutes(time.getMinutes() + num * 2))
			const takeTime = getNowFormatDate(nTime)
			// 生成取餐码
			const code = Math.floor(Math.random() * 700 + 800)
			console.log('time====>', time)
			const updateResult = await db.collection('orders').where({order_id}).update({
				createOrderTime: nowTime,
				takeTime: takeTime,
				sort_num: code,
				status: 3
			})
			
			const fields = {
				chooseStore: 1,
				order_id: 1, // 用户和时间编译的订单号
				order_type: 1, // 0为自取订单,1为外卖
				goodsInOrder: 1, // 购物车列表
				totalFee: 1, // 订单总价
				status: 1,
				createOrderTime: 1,
				takeTime: 1,
				remark: 1,
				payment_channel: 1,
				sort_num: 1
			}
			
			// 查询封装数据类型输出
			const resResult = await db.collection('orders').where({order_id}).field(fields)
			.get().then(res => {
				return res.data[0]
			})
			resResult.peopleNum = num
			if(updateResult.id || updateResult.updated === 1) {
				return {
					'status': 0,
					'data': resResult
				}
			} else {
				return {
					'status': 1,
					'msg': '后台数据错误'
				}
			}
		} else if(status === 3 || status === 4 || status === 5) {
			const fields = {
				chooseStore: 1,
				order_id: 1, // 用户和时间编译的订单号
				order_type: 1, // 0为自取订单,1为外卖
				goodsInOrder: 1, // 购物车列表
				totalFee: 1, // 订单总价
				status: 1,
				createOrderTime: 1,
				takeTime: 1,
				remark: 1,
				payment_channel: 1,
				sort_num: 1
			}
			// 查询封装数据类型输出
			const resResult = await db.collection('orders').where({order_id}).field(fields)
			.get().then(res => {
				return res.data[0]
			})
			
			return {
				'status': 1,
				'data': resResult
			}
		}
	} else if(event.action === 'orderUpdate') {
		let order_id = event.order_id
		//判断status状态
		const status = await db.collection('orders').where({order_id}).field({status:1})
		.get().then(res => {
			return res.data[0].status
		})
		
		return status
	}
};
